<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Index extends CI_Controller{
	/**
     * 构造函数
     *
     * @access  public
     * @return  void
     */
	public function __construct(){
		parent::__construct();
	}

	//判断附件是否存在
	function att_exist(){
		$arr = $this->input->post();
		$att_name = iconv( "UTF-8", "GB2312" , urldecode($arr['filen']));	
		$find = array("&#40;","&#41;");
		$replace = array("(",")");
		$att_name = str_replace($find,$replace,$att_name);
		
		//拼接文件绝对地址路径并转码
		$file_dir = FCPATH.'attach\\'.$arr['m'].'\\'.$arr['ym'].'\\'.$arr['rand'].'.'.$att_name;
		
		//判断文件是否存在，否则停止执行并提示
		if(!file_exists($file_dir)){
			echo json_encode(array("success"=>false)); 
		}else{
			echo json_encode(array("success"=>true)); 
		}
	}

	function user_list(){
		$this->db->select('user_id,user_name,dept_id');
 		$this->db->join('role', 'users.role_id = role.role_id','left');
		
		$this->db->order_by('dept_id asc,role_sort asc, user_sort asc'); 
		$query=$this->db->get('users');
		
		foreach ($query->result() as $v){
			$rowdept = $this->user_m->deptlist($v->dept_id);
			$arrset[] = array("userid"=>$v->user_id,"username"=>$v->user_name,"dept_name"=>$rowdept[0]['text'],);
		}
		$result = json_encode($arrset);
		$callback=$_GET['jsoncallback'];  
		echo $callback."($result)";   
	}
	
	function check_up(){
		$u_id =  $this->input->post('u');
		$query = $this->db->select('id,u_name,m_id')->where('u_id',$u_id)->where('check_read',0)->get('sms_check');
		$row = $query->first_row();
		
		if(!empty($row)){
			$m_str = explode('_',$row->m_id);
			$data = array('sms_read' => '1');
			$this->db->where('smsid', end($m_str));
			$this->db->update('sms', $data); 
			$arr['success'] = true;
			$arr['toName'] = $row->u_name;
			$arr['mType'] = reset($m_str);
			
			$this->db->where('id',$row->id)->delete('sms_check');

		}else{
			$arr['success'] = false;
		}
		echo json_encode($arr);
	}



	function upload_file(){
		$attach_id = '';
		$attach_name = '';
		$filesize = '';
		
		$to_id = $this->input->get_post('to_id');
		$to_idarr = explode(",",$to_id);
		//$to_idarr = json_decode($to_idarr);
		$to_name = $this->input->get_post('to_name');
		$to_namearr = explode(",",$to_name);
		//$to_namearr = json_decode($to_namearr);
		//$to_name = implode(',',$to_namearr).",";
		
		$user_name = $this->input->get_post('user_name');
		//$user_name = urldecode($user_name);
		
		$title = $this->input->get_post('title');
		//$title = urldecode($title);
		$content = $this->input->get_post('content');
		//$content = urldecode($content);
		$user_id = $this->input->get_post('user_id');
		$sendertime = date("Y-m-d H:i:s",time());

		
		//$to_id = implode(',',$to_idarr).",";
		
		
		
		if ($_FILES){//如果上传文件
			//提取允许的附件类型
			$query = $this->db->select('attachment_type')->get('site_settings');
			$row = $query->row()->attachment_type; 
			$attachment_type = explode(",",$row);
			
			//print_r($_FILES);	
			// 验证文件类型
			//$fileTypes = array('jpg','jpeg','gif','png','psd','bmp','doc','docx','xls','xlsx','ppt','pptx','mp3','mp4','avi','mpg','mpeg','wma','wav','rm','rmvb','swf','flv','rar','zip','7z','exe','apk'); // 文件扩展名
			$datedir = date('ym');
			$newemailrand = mt_rand(000000000,999999999);
			$targetFolder = FCPATH . 'attach/email/'.$datedir.'/'; // 相对于根
			if(!is_dir($targetFolder)) mkdir($targetFolder, 0755); 
			$attach_id = $datedir.'_'.$newemailrand.',';

			//$filename = $_FILES["file"]["name"];
			$filename = $_FILES["file"]["name"];			
			$filename = urldecode($filename);
			$filesize = $_FILES["file"]["size"].',';
			
			$suffix = end(explode(".",$filename));//按空格截取
			if (!in_array($suffix,$attachment_type)) {
				$filename = $filename.'.jpg';
			}
			$attach_name = $filename.'*';
			$filename = iconv("UTF-8","GBK",$filename);
			$targetFile = $targetFolder . $newemailrand.'.'. $filename;
			
			move_uploaded_file($_FILES["file"]["tmp_name"],$targetFile);
		}


		$array = array(//邮件主体数据
			'bodyid' => '', 
			'senderid' => $user_id, 
			'sender' => $user_name, 
			'addressee2' => $to_name,
			'cc' => '', 
			'title'=> $title,
			'content'=> $content,
			'sendertime'=> date("Y-m-d H:i:s",time()),
			'attachment_id'=> $attach_id,
			'attachment_name'=> $attach_name,
			'smsalerts'=> '1',
			'important'=> '0',				
			'size'=> $filesize
		);
		$this->db->set($array);
		$this->db->insert('email_body'); //插入邮件主体
		$bodyid = $this->db->insert_id();

		//邮件短信提醒数据主体插入到数据库			
		$smsarr = array(
			'bodyid' => '' ,
			'sender' => $user_name,
			'smstype' => '2',
			'alerttype' => '0',
			'content' => '请查收我的邮件！ 主题：'.$title,
			'sendtime' => date("Y-m-d H:i:s",time()),
			'remindurl' => 'email/inbox/'.$bodyid
		 ); 
		$this->db->insert('sms_body', $smsarr); //插入短信提醒主体数据
		$bodyid2 = $this->db->insert_id();

		
		//$addressee = explode(",",substr($data['p_sj_user'],0,-1));
		for($i = 0; $i<count($to_idarr);$i++){
			$arr[0][] = array(//邮件收件人数据
				'emailid' => '',
				'userid' => $to_idarr[$i],
				'addressee' => $to_namearr[$i],
				'read' => '0',
				'readtime' => '',
				'delete' => '0',
				'bodyid' => $bodyid
			);

			$arr[1][] = array(//短信收信人数据
				'smsid' => '',
				'to_id' => $to_idarr[$i],
				'to_name' => $to_namearr[$i],
				'sms_read' => '0',
				'readtime' => '',
				'sms_delete' => '0',
				'bodyid' => $bodyid2
			);
			$arr[2][] = array(//用于检索的数据表数据
				'id' => '',
				'u_id' => $to_idarr[$i],
				'u_name' => $to_namearr[$i],
				'add_date' => time(),
				'm_id' => '2_'.$bodyid2
			);

		}
		$this->db->insert_batch('email',$arr[0]); //插入接收邮件数组
		$this->db->insert_batch('sms',$arr[1]); //插入接收邮件数组
		$this->db->insert_batch('sms_check',$arr[2]); //插入接收邮件数组

		$arrset = array("str"=>true);
		echo json_encode($arrset);
		//echo  $_GET['jsoncallback'].'('.$result.')'; 
	}
	
	function search_res_list(){
		$content = array();
		//$username = $this->input->get('username');
		//$username = urldecode($username);
		
		$userid = $this->input->get('userid');	
		$m_v = $this->input->get('m_v');		
		$StartNum = $this->input->get('page');
		
		$search_key = $this->input->get('search_key');
		$search_key = urldecode($search_key);
		
		$pagesize=10;
		if($StartNum < 0){
			$StartNum = 1;
		}
		$start=($StartNum-1)*$pagesize;
		$this->db->from('email');
		$this->db->join('email_body', 'email_body.bodyid = email.bodyid');
		$this->db->where('email.userid', $userid);
		
		$names = array('0', '4');
 		$this->db->where_in('email.delete', $names);
		$this->db->like('email_body.title', $search_key); 
		$this->db->order_by("email.emailid", 'desc'); 
		$this->db->limit($pagesize,$start);
		$query=$this->db->get();
		//echo $this->db->last_query();//输出随后一次查询的语
		foreach ($query->result() as $v){
			$st = reset(explode(' ',$v->sendertime));
			$isa = $v->attachment_id?1:0;
			$content[] = array("id"=>$v->emailid,"s"=>$v->sender,"t"=>$v->title,"r"=>$v->read,"st"=>$st,"bodyid"=>$v->bodyid,'isa'=>$isa);

		}
		$arrset['result'] = $content;
		//$arrset['a_count'] = count($content);
		//$arrset['startNum'] = ++$StartNum;
		
		$result = json_encode($arrset);
		//$callback=$_GET['jsoncallback'];  
		$callback=$this->input->get('callback');
		echo $callback."($result)";  
	
	}

}